<?php

namespace App\Http\Controllers;

use App\Events\ProfileChange;
use App\Models\Balance;
use App\Models\Buy;
use App\Models\Cancel;
use App\Models\Sell;
use App\Models\Seller;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class SellerController extends Controller
{
  public function indexForAdmin(Request $request)
  {
    $page = User::when($request->has('code'), function ($q) use ($request) {
      $q->where('code', $request->code);
    })
      ->when($request->has('created_at'), function ($q) use ($request) {
        $range = getRange($request->created_at);
        $q->whereBetween('created_at', $range);
      })
      ->when($request->has('username'), function ($q) use ($request) {
        $q->where('username', $request->username);
      })
      ->whereNull('pid')
      ->where('role', 'seller')
      ->latest()
      ->page();

    $page->transform(function ($item) {
      $item->makeVisible('code');
      return $item;
    });
    return success($page);
  }

  public function accounts(Request $request)
  {

    $page = $this->accountQueryBuilder($request)
      ->latest()
      ->page();

    $page->transform(function ($item) {
      $item->seller_sells_sum_coins += 0;
      $item->seller_buys_sum_coins += 0;
      $item->seller_buys_sum_fee += 0;
      $item->seller_buys_sum_tip += 0;
      $item->seller_buys_done_sum_coins += 0;
      $item->seller_buys_undone_sum_coins += 0;
      return $item;
    });

    $all = $this->accountQueryBuilder($request)->get();

    $footer = [
      '汇总',
      '',
    ];

    $sums = [
      'seller_sells_sum_coins',
      'seller_buys_sum_coins',
      'seller_buys_sum_fee',
      'seller_buys_sum_tip',
      'seller_buys_done_sum_coins',
      'seller_buys_done_count',
      'seller_buys_undone_sum_coins',
      'seller_buys_undone_count',
    ];

    foreach ($sums as $name) {
      $footer[] = (float) $all->sum($name);
    }

    return success($page, $footer);
  }

  protected function accountQueryBuilder($request)
  {
    return User::select('id', 'username')
      ->when($request->has('username'), function ($q) use ($request) {
        $q->where('username', $request->username);
      })
      ->when($request->has('created_at'), function ($q) use ($request) {
        $range =  getRange($request->created_at);

        $q->withSumBetween('sellerSells', 'coins', $range, 'updated_at')
          ->withSumBetween('sellerBuys', 'coins', $range, 'updated_at')
          ->withSumBetween('sellerBuys', 'fee', $range, 'updated_at')
          ->withSumBetween('sellerBuys', 'tip', $range, 'updated_at')
          ->withSumBetween('sellerBuysDone', 'coins', $range, 'updated_at')
          ->withSumBetween('sellerBuysUndone', 'coins', $range, 'updated_at')
          ->withCountBetween(['sellerBuysDone'], $range, 'updated_at')
          ->withCountBetween(['sellerBuysUndone'], $range, 'updated_at');
      }, function ($q) {
        $q->withSum('sellerSells', 'coins') // 买币
          ->withSum('sellerBuys', 'coins') // 卖币
          ->withSum('sellerBuys', 'fee') // 手续费
          ->withSum('sellerBuys', 'tip') // 奖励
          ->withSum('sellerBuysDone', 'coins') // 已处理金额
          ->withSum('sellerBuysUndone', 'coins') // 未处理金额
          ->withCount(['sellerBuysDone', 'sellerBuysUndone']);
      })
      ->where([
        'role' => 'seller',
        'pid' => null
      ]);
  }

  public function store(Request $request)
  {
    $exists = User::where('username', $request->username)->exists();
    if ($exists) {
      fail('用户名重复');
    }
    $inputs = $request->all();
    $inputs['password'] = bcrypt('88888888');
    $inputs['role'] = 'seller';
    $inputs['api_token'] = \Str::uuid();
    $inputs['code'] = makeCode();

    User::create($inputs);

    return success('ok');
  }

  public function update(Request $request, $id)
  {
    \DB::transaction(function () use ($id, $request) {
      $seller = User::lockForUpdate()->findOrFail($id);
      if ($request->filled('password')) {
        $seller->password = bcrypt($request->password);
      }
      $seller->enable = $request->enable;
      $seller->fee_ratio = $request->fee_ratio;
      $seller->tip = $request->tip;
      $seller->mobile = $request->mobile;
      $seller->save();

      // $seller->createLog($request->all());
    });
    event(new ProfileChange($id));
    return success('ok');
  }

  public function adjustCoins(Request $request, $id)
  {
    \DB::transaction(function () use ($id, $request) {
      $seller = User::lockForUpdate()->findOrFail($id);
      $seller->coinsChange($request->top_up, $request->top_up > 0 ? '人工加币' : '人工减币');
    });
    event(new ProfileChange($id));
    return success('ok');
  }

  public function destroy($id)
  {
    $seller = User::findOrFail($id);
    $seller->oprationLogs()->delete();

    return success('ok');
  }

  protected function getSumUids($key, $relation, $field)
  {
    return User::where([
      'role' => 'seller',
      'pid' => null
    ])
      ->select('id', 'username')
      ->withSum($relation, $field)
      ->get()
      ->filter(function ($seller) use ($key) {
        return $seller->{$key} >= request($key);
      })
      ->pluck('id')
      ->all();
  }
}
